package com.ssyc.student.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.flowlayout.FlowLayout;
import com.ssyc.common.view.flowlayout.TagAdapter;
import com.ssyc.common.view.flowlayout.TagFlowLayout;
import com.ssyc.common.view.flowlayout.TagView;
import com.ssyc.student.R;
import com.ssyc.student.bean.ErrorQuestionsInfo;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--语法错题集--连词成句fragment
 * Created by Kevin on 2018/5/30
 */

public class StudentErrorConjunctionsFragment extends LazyBaseFragment implements View.OnClickListener {


    //提供选项的数据集合
    private List<String> answerInfos;

    //当前题目的位置
    private int currPos;

    //流式布局
    public TagFlowLayout mFlowLayout;

    //显示选择内容
    private TextView tv_content;

    //流式布局适配器
    private TagAdapter adapter;

    //题目内容
    private List<ErrorQuestionsInfo.DataBean.ErrorListBean> datas;

    //答案
    private TextView tv_show_answer;

    //班级正确率
    private TextView tv_class_accuracy;

    //全校正确率
    private TextView tv_school_accuracy;

    //移除
    private ImageView iv_del;

    //正误
    private ImageView iv_answerTF;

    //超越目标
    private TextView tv_overshoot;

    //未答对学生
    private TextView tv_notright_stu;

    //移除题目后刷新数据
    public static final String DELREFLASH = "delreflash";

    /**
     * 提供的生成当前Fragment的方法
     *
     * @param data 包含页面数据的json字符串
     * @return
     */
    public static StudentErrorConjunctionsFragment newInstance(String data, int pos) {

        StudentErrorConjunctionsFragment studentErrorConjunctionsFragment = new StudentErrorConjunctionsFragment();
        Bundle bundle = new Bundle();
        bundle.putString("data", data);
        bundle.putInt("pos", pos);
        studentErrorConjunctionsFragment.setArguments(bundle);

        return studentErrorConjunctionsFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_student_error_conjunctions;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {
        //初始化视图
        initView(view);

        showContent();

        //答案选项的数据
        initData();

        //设置展示答案的ListView
        initLv();
    }


    /**
     * 初始化视图
     *
     * @param view
     */
    public void initView(View view) {
        iv_answerTF = view.findViewById(R.id.iv_answerTF);

        mFlowLayout = view.findViewById(R.id.id_flowlayout);

        tv_content = view.findViewById(R.id.tv_content);

        tv_show_answer = view.findViewById(R.id.tv_show_answer);

        tv_class_accuracy = view.findViewById(R.id.tv_class_accuracy);

        tv_school_accuracy = view.findViewById(R.id.tv_school_accuracy);

        tv_overshoot = view.findViewById(R.id.tv_overshoot);

        tv_notright_stu = view.findViewById(R.id.tv_notright_stu);

        iv_del = view.findViewById(R.id.iv_del);

        iv_del.setOnClickListener(this);
    }


    /**
     * 答案选项
     */
    private void initData() {


        //获取当前页面的位置
        currPos = getArguments().getInt("pos");

        //获取传递过来的页面数据
        String dataJson = getArguments().getString("data");
        //解析该Json获取页面数据
        datas = new ArrayList<>();
        datas = GsonUtil.jsonToBean(dataJson, ErrorQuestionsInfo.DataBean.class).getError_list();
        answerInfos = datas.get(currPos).getOptions();

        //设置正确答案
        tv_show_answer.setText(datas.get(currPos).getAnswer());
        //设置我的作答
        tv_content.setText(datas.get(currPos).getExplain());
        //设置班级正确率
        tv_class_accuracy.setText("班级正确率：" + datas.get(currPos).getClass_correct() + "%");
        //设置学校正确率
        tv_school_accuracy.setText("全校正确率：" + datas.get(currPos).getSchool_correct() + "%");

        //是否是教师端
        if ("2".equals(AccountUtils.getRole(getActivity()))) {
            tv_overshoot.setVisibility(View.VISIBLE);
            tv_notright_stu.setVisibility(View.VISIBLE);
            iv_del.setVisibility(View.GONE);
            iv_answerTF.setVisibility(View.GONE);

            //设置超越目标
            if (datas.get(currPos).getTranscend().size() != 0) {
                String temp = "";
                for (int i = 0; i < datas.get(currPos).getTranscend().size(); i++) {
                    temp = datas.get(currPos).getTranscend().get(i) + " ";
                }
                tv_overshoot.setText("超越目标：" + temp);
            } else {
                tv_overshoot.setText("超越目标：暂无");
            }

            //设置未答对人
            if (datas.get(currPos).getStu_error().size() != 0) {
                String tem = "";
                for (int i = 0; i < datas.get(currPos).getStu_error().size(); i++) {
                    tem = datas.get(currPos).getStu_error().get(i) + " ";
                }
                tv_notright_stu.setText("未答对人：" + tem);
            } else {
                tv_notright_stu.setText("未答对人：暂无");
            }
        }

    }

    /**
     * 设置流式布局
     */
    private void initLv() {

        final LayoutInflater mInflater = LayoutInflater.from(getActivity());

        adapter = new TagAdapter<String>(answerInfos) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) mInflater.inflate(R.layout.stu_grammar_conjunctions_tv,
                        mFlowLayout, false);
                tv.setText(s);
                return tv;
            }

            @Override
            public void onSelected(int position, View view) {

                super.onSelected(position, view);

                ((TextView) view).setTextColor(getResources().getColor(R.color.white));
            }

            @Override
            public void unSelected(int position, View view) {
                super.unSelected(position, view);
                ((TextView) view).setTextColor(getResources().getColor(R.color.black));
            }
        };

        //添加适配器
        mFlowLayout.setAdapter(adapter);

        //关闭交互
        for (int i = 0; i < mFlowLayout.getChildCount(); i++) {

            TagView tagView = (TagView) mFlowLayout.getChildAt(i);
            tagView.setEnabled(false);
        }
    }

    /**
     * 点击事件
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_del) {
            //移除按钮
            //弹框
            PopUpManager.showPop(getActivity(), R.layout.st_pop_error_quetions,
                    0.3f, getActivity(), new PopUpManager.onGetViewListener() {
                        @Override
                        public void getChildView(View view, int layoutResId) {
                            //关闭按钮
                            ImageView ivClose = view.findViewById(R.id.lv_close);
                            Button btCommit = view.findViewById(R.id.bt_commit);
                            ivClose.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    //关闭弹框
                                    PopUpManager.dismiss();
                                }
                            });
                            btCommit.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    //移除题目
                                    delErrorQuestions();
                                    //关闭弹框
                                    PopUpManager.dismiss();
                                }
                            });
                        }
                    });
        }
    }

    /**
     * 移除错题
     */
    private void delErrorQuestions() {

        Map<String, String> map = new HashMap<>();
        map.put("type", "33");
        map.put("acc", AccountUtils.getAccount(getActivity()));
        map.put("role", AccountUtils.getRole(getActivity()));
        map.put("lessonId", datas.get(currPos).getLessonId().replace("Lesson", ""));
        map.put("moduleId", datas.get(currPos).getModuleId());
        map.put("typeId", datas.get(currPos).getTypeId());
        map.put("questionId", datas.get(currPos).getQuestionId());
        map.put("apptoken", AccountUtils.getToken(getActivity()));
        map.put("platform", "8");
//        map.put("acc", "15608630008");
//        map.put("lessonId", "1");
//        map.put("apptoken", "WHBHWJDSAKDAKSDNSAJDAK");

        Log.i("test", "lessonId:" + datas.get(currPos).getLessonId() + "moduleId:" + datas.get(currPos).getModuleId() +
                "typeId:" + datas.get(currPos).getTypeId() + "questionId:" + datas.get(currPos).getQuestionId());
        HttpUtils.post(HttpAdress.ERRORQUESTIONS, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast("网络错误", false);
            }

            @Override
            public void onResponse(String response, int id) {
                showContent();
                ErrorQuestionsInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, ErrorQuestionsInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("test", "数据解析异常");
                }
                Log.i("test", "错题集：" + response);
                if (null != info) {
                    if ("200".equals(info.getState())) {
                        //返回成功
                        UiUtils.Toast("移除成功", false);
                        //EventBus通知Activity进行移除界面
                        EventBus.getDefault().post(new BusInfo(DELREFLASH, currPos));
                    } else {
                        Log.i("test", info.getState());
                        UiUtils.Toast("移除失败", false);
                    }
                }
            }
        });
    }
}
